package com.zjw.zy.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.zjw.zy.base.BaseViewModel
import com.zjw.zy.bean.MemorandumItem
import com.zjw.zy.datasource.database.AppDataBase
import com.zjw.zy.ext.dateString
import com.zjw.zy.ext.onIo

/**
 * @author     ：zhong.jw
 * @date       ：Created in 2022/9/30 13:51
 * @description：备忘录数据ViewModel
 */
class MemorandumViewModel : BaseViewModel() {


    private val mMemorandumData: MutableLiveData<List<MemorandumItem>> = MutableLiveData()
    fun getData(): LiveData<List<MemorandumItem>> = mMemorandumData


    fun requestMemorandumData() {
        onIo {
            val data = AppDataBase.getInstance().memorandumDao().queryAll()
            mMemorandumData.postValue(data)
        }
    }

    fun addMemorandumData(item: MemorandumItem) {
        onIo {
            AppDataBase.getInstance().memorandumDao().insertItem(item)
        }
    }


    fun deleteMemorandumData(item: MemorandumItem) {
        onIo {
            AppDataBase.getInstance().memorandumDao().deleteItem(item)
        }
    }


    fun updateMemorandumData(item: MemorandumItem) {
        onIo {
            AppDataBase.getInstance().memorandumDao().updateItem(item)
        }
    }

    fun queryByKeyWord(keyword: String) {
        onIo {
            val data = AppDataBase.getInstance().memorandumDao().queryAll()

            if (keyword.isEmpty()) {
                mMemorandumData.postValue(data)
                return@onIo
            }

            val validData = ArrayList<MemorandumItem>()

            for (item in data) {
                if (item.title.contains(keyword) || item.text.contains(keyword) || item.date.dateString()
                        .contains(keyword)
                ) {
                    validData.add(item)
                }
            }

            mMemorandumData.postValue(validData)
        }
    }
}